package com.second.app.thread.stream.io;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author gyz
 * @date 2021/1/27 13:43
 * <p>
 * 一个数字占用一个字节，一个英文字母占一个字节。
 * 假设定义一个长度为30的字节数组，然后将文件转换成文件流。调用read()方法，每次读取30个字节。
 * 直到读取到文件流末尾的最后一个字节，返回-1，
 */
public class FileReadWriteExample {

    private static final String separator = File.separator;

    private static final byte[] bytes = new byte[1024];

    /**
     * 文件 字节流的读写
     */
    public static void readFromFile() {
        try {
            //文件来源
            FileInputStream fileInputStream = new FileInputStream("D:" + separator + "read.txt");
            //文件输出目标地址
            FileOutputStream fileOutputStream = new FileOutputStream("D:" + separator + "readCopy.txt");
            int len = fileInputStream.read(bytes);
            StringBuilder sb = new StringBuilder();
            while (len != -1) {
                //将指定字节数组中的<code> b.length <code>个字节写入此文件输出流
                fileOutputStream.write(bytes);
                String str = new String(bytes, 0, len);
                sb.append(str);
                len = fileInputStream.read(bytes);
            }
            System.out.println("输出的文件内容为:" + sb);
            fileOutputStream.flush();
            fileInputStream.close();
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载文件到浏览器
     */
    public static void downLoadFileToExplorer(HttpServletRequest request, HttpServletResponse response) throws IOException {
        File file = new File("D:" + separator + "read.txt");
        ServletOutputStream outputStream = response.getOutputStream();
        FileInputStream fileInputStream = null;
        if (file.isFile()) {
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;fileName=" + file.getName());
            fileInputStream = new FileInputStream(file);
            int len = 0;
            while (len != fileInputStream.read(bytes)) {
                fileInputStream.read(bytes);
                outputStream.write(bytes);
            }
        }
        outputStream.flush();
        outputStream.close();
        fileInputStream.close();
    }

    public static void main(String[] args) {
        int a, b, c;
        a = 'a';
        b = 'b';
        c = (a + b > 180 ? a++ : b++);
        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
    }


}


